import { DataTableMethods, UseTableReturnType, GetanTableProps } from "./types"

export function useGetanTable(props: GetanTableProps): UseTableReturnType {
    const modalRef = ref<Nullable<DataTableMethods>>(null)

    const getInstance = () => {
        const instance = unref(modalRef.value)
        if (!instance) {
            console.error("useModal instance is undefined!")
        }
        return instance
    }

    const register = (modalInstance: DataTableMethods) => {
        modalRef.value = modalInstance
        modalInstance.init && modalInstance.init(props)
    }

    const methods: DataTableMethods = {
        loadData: () => getInstance()?.loadData(),
        setTableData: tableData => getInstance()?.setTableData(tableData),
        getTableData: () => getInstance()?.getTableData() ?? [],
        setFilterConditions: conditions => getInstance()?.setFilterConditions(conditions)
    }

    return { register, methods }
}
